import { toLogin } from ".";

const token = {
  access: null,
  refresh: null,
  time: Date.now(),
  exists() {
	  return !!this.access;
  },
  load() {
	  const token = JSON.parse(uni.getStorageSync('token') || '{}');
	  this.access = token.access;
	  this.refresh = token.refresh;
	  this.time = token.time;
  },
  save(res) {
	  if (res.code == 2000) {
		  const token = res.data;
		  const time = Date.now();
		  uni.setStorageSync('token', JSON.stringify({
			  access: token.access,
			  refresh: token.refresh,
			  time 
		  }));
		  this.access = token.access;
		  this.refresh = token.refresh;
		  this.time = time;
	  }
  },
  needRefresh() {
	  if (!this.refresh) {
		  return false;
	  }
	  const escapedTime = Date.now() - this.time;
	  if (escapedTime > 1439 * 60000) {
		  return true;
	  }
	  
	  return false;
  },
  clear() {
	  uni.removeStorageSync('token');
	  this.access = null;
	  this.refresh = null;
  },
  check() {
	  if (!this.exists()) {
		  toLogin();
		  return true;
	  }
	  return false;
  }
};

export default token;